package com.echronos.payment.commons.cpcn.util;

import com.alibaba.fastjson.JSONObject;
import com.echronos.commons.exception.BusinessException;
import com.echronos.payment.enums.CpcnTxCodeEnums;
import cpcn.institution.tools.net.RequestDgtEnvlp;
import cpcn.institution.tools.util.Base64;
import cpcn.institution.tools.util.DigitalEnvelopeUtil;
import cpcn.institution.tools.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import payment.api.system.PaymentEnvironment;
import payment.api.system.TxMessenger;

import java.io.File;
import java.util.Properties;

/**
 * cpcn支付交易skd
 *
 * @Author wangyadong
 * @Date 2023/10/25 15:24
 * @ClassName CpcnAbstractClinet
 */
@Slf4j
public class CpcnAbstractClient implements CpcnClient {
    /**
     * 机构号
     */
    private String institutionID;

    public CpcnAbstractClient(String institutionID) {
        this.institutionID = institutionID;
    }

    public static Properties properties;

    @Override
    public <T extends CpcnResponse> T execute(CpcnPayRequest<T> request) {
        try {
            // 证书的路径
//            String paymentConfigPath = "/cert/cpcn/" + institutionID;
            String paymentConfigPath = File.separatorChar + "app" + File.separatorChar + "cert" + File.separatorChar
                    + "cpcn" + File.separatorChar + institutionID;
            // 初始化支付环境
            try {
                PaymentEnvironment.initialize(paymentConfigPath);
//                ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//                Resource[] resources = resolver.getResources(paymentConfigPath);
//                Resource resource = resources[0];
//                String absolutePath = resource.getURL().getFile();
//                log.info("临时文件夹目录地址1：{}", absolutePath);
//                PaymentEnvironment.initialize(absolutePath);
            } catch (Exception e) {
                log.error("唤起中金异常：{}", e);
                log.info("临时文件夹目录地址2：{}", paymentConfigPath);
                PaymentEnvironment.initialize(paymentConfigPath);
            }
            JSONObject businessBiz = request.getBusinessBiz();
            String message = businessBiz.getString("requestMessage");
            String signature = businessBiz.getString("requestSignature");
            String requestPlainText = businessBiz.getString("requestPlainText");
            String txCode = businessBiz.getString("txCode");
            RequestDgtEnvlp requestDgtEnvlp = businessBiz.toJavaObject(RequestDgtEnvlp.class);
            requestDgtEnvlp.setIsDgEnv(PaymentEnvironment.isDgEnv);
            // 与支付平台进行通讯
            TxMessenger txMessenger = new TxMessenger();
            if (!CpcnTxCodeEnums.PHOTO_COPY_COLLECTION.getCode().equals(txCode)) {
                //影印件采集的base64日志太多了，不打印了
                log.info("请求中金XML原文:{}", requestPlainText);
            }
            String[] respMsg = txMessenger.send(message, signature, requestDgtEnvlp, request.cpcnGatewayUrl());
            String plainText;
            if ("YES".equals(respMsg[2])) {
                //如果响应是数字信封，对消息进行对称解密
                try {
                    log.info("开始对响应消息做对称解密。。。。。。");
                    if ("YES".equals(PaymentEnvironment.isDoubleCert)) {
                        log.info("双证解密。。。。。。");
                        respMsg[0] = DigitalEnvelopeUtil.doubleDecryptResponse(respMsg[0], respMsg[3], respMsg[5], respMsg[6]);
                    } else {
                        respMsg[0] = DigitalEnvelopeUtil.decryptResponse(respMsg[0], respMsg[3], respMsg[5], respMsg[6]);
                    }
                    plainText = respMsg[0];
                    respMsg[0] = Base64.encode(respMsg[0], "UTF-8");
                    respMsg[0] = respMsg[0] + "," + respMsg[5] + "," + respMsg[4] + "," + respMsg[2];
                    log.info("响应消息做对称解密完成。。。。。。");
                    log.info("响应消息报文：[" + plainText + "]");
                } catch (Exception e) {
                    throw new Exception(e + "对称解密异常！");
                }
            } else {
                // 1:signature
                plainText = new String(cpcn.institution.tools.util.Base64.decode(respMsg[0]), "UTF-8");
                if (StringUtil.isNotEmpty(respMsg[5])) {
                    respMsg[0] = respMsg[0] + "," + respMsg[5] + "," + respMsg[4] + "," + respMsg[2];
                }
            }
            JSONObject responseStr = request.verifier(respMsg[0], respMsg[1]);
            Class<T> clazz = request.getResponseClass();
            T t = responseStr.toJavaObject(clazz);
            t.setIsSuccess(Boolean.TRUE);
            t.setReq(message);
            t.setResp(JSONObject.toJSONString(respMsg));
            return t;
        } catch (Exception e) {
            log.error("中金支付sdk环境异常error：{}", e);
            throw new BusinessException(20000, "唤醒中金支付异常");
        }
    }

    static {
        properties = new Properties();
    }
}
